
--[[
--游戏界面
]]
local GameScene = class("GameScene", cc.load("mvc").ViewBase)

function GameScene:onCreate()
    self:addChild(cc.LayerColor:create(ColorCfg.white), 0)
    self.gridLayer = cc.LayerColor:create(ColorCfg.grey)
    self.gridLayer:setContentSize(display.width, display.width)
    self.gridLayer:setAnchorPoint(0.5,0.5)
    self.gridLayer:ignoreAnchorPointForPosition(false)
    self.gridLayer:setPosition(display.cx, display.cy)
    self:addChild(self.gridLayer, 10)
    self:initGrid()
    self:initTouchEvent()

    --当前得分
    self.score = cc.UserDefault:getInstance():getIntegerForKey("highLevelScore", 0)
    --最高分
    self.highScore = cc.UserDefault:getInstance():getIntegerForKey("highScore", 0)
    print("self.highScore", self.highScore)
    --当前关卡
    self.level = cc.UserDefault:getInstance():getIntegerForKey("highLevel", 1)
    self:initUi()
    self:refreshScore()
    self:refreshLevelInfo()
end

--初始化界面
function GameScene:initUi()

    -- 分数
    self.scoreLabel = cc.Label:create()
    self.scoreLabel:setTextColor(ColorCfg.orange)
    self.scoreLabel:setSystemFontSize(150)
    self.scoreLabel:setPosition(display.cx, display.height/2 + self.gridLayer:getContentSize().height/2)
    self.scoreLabel:setAnchorPoint(0.5, 0)
    self:addChild(self.scoreLabel, 10)
    -- 关卡信息
    self.levelInfoLabel = cc.Label:create()
    self.levelInfoLabel:setTextColor(ColorCfg.orange)
    self.levelInfoLabel:setSystemFontSize(60)
    self.levelInfoLabel:setPosition(20, display.height)
    self.levelInfoLabel:setAnchorPoint(0, 1)
    self:addChild(self.levelInfoLabel, 10)
    -- 提示信息
    self.tipLayer = cc.LayerColor:create(ColorCfg.white)
    self.tipLayer:setContentSize(display.width, display.width/3)
    self.tipLayer:setAnchorPoint(0.5,0.5)
    self.tipLayer:ignoreAnchorPointForPosition(false)
    self.tipLayer:setOpacity(0)
    self.tipLayer:setPosition(display.cx, display.cy)
    self:addChild(self.tipLayer, 40)
    self.tipLabel = cc.Label:create()
    self.tipLabel:setTextColor(ColorCfg.orange)
    self.tipLabel:setSystemFontSize(100)
    self.tipLayer:addChild(self.tipLabel, 10)
    -- 将获得的分数，仅用于双击模式
    self.preScoreLabel = cc.Label:create()
    self.preScoreLabel:setTextColor(ColorCfg.white)
    self.preScoreLabel:setSystemFontSize(60)
    self.preScoreLabel:setVisible(false)
    self:addChild(self.preScoreLabel, 10)
    self:initMenu()
end
-- 初始化菜单
function GameScene:initMenu()
    self.closeButton = Util.newButton("close.png", 1.3, cc.p(display.width / 5 * 4.5, 100), function()
        if self.disableRestartAndClose then return end
        Util.createDialog("确定要退出游戏吗？","退出游戏", function() self:getApp():enterScene("MainScene") end, "再玩一会儿", function() print("no exit") end)
    end)
    self.closeButton:setColor(ColorCfg.white)
    self:addChild(self.closeButton, 20)
    self.restartButton = Util.newButton("restart.png", 1.3, cc.p(display.width / 5 * 3.5, 100), function()
        if self.disableRestartAndClose then return end
        Util.createDialog("确定要重新开始本关吗？","重新本关", handler(self, self.restartGame), "取消", function() print("no exit") end)
    end)
    self:addChild(self.restartButton, 20)
    self.rankButton = Util.newButton("rank.png", 1.3, cc.p(display.width / 5 * 2.5, 100), function()
        if self.score > self.highScore then
            -- 破记录了
            self.highScore = self.score
            cc.UserDefault:getInstance():setIntegerForKey("highScore", self.highScore)
            cc.UserDefault:getInstance():flush()
        end
        local deviceId = cc.UserDefault:getInstance():getStringForKey("deviceid", "0")
        cc.Application:getInstance():openURL(GameCfg.rankUrl
                .."?imei="
                ..deviceId
                .."&score="
                ..self.highScore
        )
    end)
    self:addChild(self.rankButton, 20)
    local clickTypeButtonPic = "one.png"
    if DOUBLE_CLICK_ENABLE then clickTypeButtonPic = "two.png" end
    self.clickTypeButton = Util.newButton(clickTypeButtonPic, 1.3, cc.p(display.width / 5 * 1.5, 100), function()
        Util.createDialog("操作方式",
            "单击消除", function()
                print("单击消除")
                DOUBLE_CLICK_ENABLE = false
                cc.UserDefault:getInstance():setBoolForKey("DOUBLE_CLICK_ENABLE", DOUBLE_CLICK_ENABLE)
                cc.UserDefault:getInstance():flush()
                self.clickTypeButton:loadTextureNormal("one.png", 0)
                self.clickTypeButton:loadTexturePressed("one.png", 0)
                self.clickTypeButton:loadTextureDisabled("one.png", 0)
                if self.isPreSelected then
                    -- 取消选中星星
                    self:diselectStar()
                    self:hidePreScore()
                    self.isPreSelected = false
                end
            end,
            "双击消除", function()
                print("双击消除")
                DOUBLE_CLICK_ENABLE = true
                cc.UserDefault:getInstance():setBoolForKey("DOUBLE_CLICK_ENABLE", DOUBLE_CLICK_ENABLE)
                cc.UserDefault:getInstance():flush()
                self.clickTypeButton:loadTextureNormal("two.png", 0)
                self.clickTypeButton:loadTexturePressed("two.png", 0)
                self.clickTypeButton:loadTextureDisabled("two.png", 0)
            end
        )
    end)
    self:addChild(self.clickTypeButton, 20)
    local musicButtonPic = "music.png"
    if not MUSIC_ENABLE then musicButtonPic = "musicOff.png" end
    self.musicButton = Util.newButton(musicButtonPic, 1.3, cc.p(display.width / 5 * 0.5, 100), function()
        Util.createDialog("声音开关",
            "开", function()
                print("开启声音")
                MUSIC_ENABLE = true
                cc.UserDefault:getInstance():setBoolForKey("MUSIC_ENABLE", MUSIC_ENABLE)
                cc.UserDefault:getInstance():flush()
                self.musicButton:loadTextureNormal("music.png", 0)
                self.musicButton:loadTexturePressed("music.png", 0)
                self.musicButton:loadTextureDisabled("music.png", 0)
            end,
            "关", function()
                print("关闭声音")
                MUSIC_ENABLE = false
                cc.UserDefault:getInstance():setBoolForKey("MUSIC_ENABLE", MUSIC_ENABLE)
                cc.UserDefault:getInstance():flush()
                self.musicButton:loadTextureNormal("musicOff.png", 0)
                self.musicButton:loadTexturePressed("musicOff.png", 0)
                self.musicButton:loadTextureDisabled("musicOff.png", 0)
            end
        )
    end)
    self:addChild(self.musicButton, 20)
end
--刷新分数
function GameScene:refreshScore()
    self.scoreLabel:setString(tostring(self.score))
end
--刷新关卡信息
function GameScene:refreshLevelInfo()
    self.levelInfoLabel:setString("第".. self.level .. "关 目标分数:"..tostring(GameCfg.calcTargetScore(self.level)))
end
function GameScene:initTouchEvent()
    local touchListener = cc.EventListenerTouchOneByOne:create()
    local eventDispatcher = self.gridLayer:getEventDispatcher()
    touchListener:registerScriptHandler(handler(self, self.onTouch), cc.Handler.EVENT_TOUCH_BEGAN)
    eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, self.gridLayer)
end
function GameScene:onTouch(touch)
    if cc.rectContainsPoint(self.gridLayer:getBoundingBox(), touch:getLocation()) then
        print("contain")
        local pos = self.gridLayer:convertToNodeSpace(touch:getLocation())
        local touchRow = math.ceil(pos.y/(self.gridLayer:getContentSize().height/GameCfg.gridRow))
        local touchCol = math.ceil(pos.x/(self.gridLayer:getContentSize().width/GameCfg.gridCol))
        print(touchRow, touchCol)
        self:touchStar(touchRow, touchCol)
    end
end
--[[
    点击一个星星
     row,col,行列
 ]]
function GameScene:touchStar(row, col)
    -- 如果点住空白
    if self.grid[row][col] == 0 then return end
    -- 如果当前有对话框在显示
    if Util.dialogLayer then return end
    if DOUBLE_CLICK_ENABLE then
        -- 双击模式
        self:touchStarForDoubleClickType(row, col)
    else
        -- 单击模式
        self:touchStarForSingleClickType(row, col)
    end
end
-- 单击模式时的处理方式
function GameScene:touchStarForSingleClickType(row, col)
    -- 相连的星星
    self.connectStars = {{row, col} }
    self:checkStar(row, col)
    if #self.connectStars >= 2 then
        self:cleanOnce(row, col)
    end
end
-- 双击模式时的处理方式
function GameScene:touchStarForDoubleClickType(row, col)

    if self.isPreSelected then
        print("已经在选中状态")
        -- 如果已经在预选状态
        -- 如果在相连数组里，就消除
        if self:connectContain(row, col) then
            self:cleanOnce(row, col)
            self:hidePreScore()
            self.isPreSelected = false
        else
            -- 取消选中星星
            self:diselectStar()
            self:hidePreScore()
            -- 相连的星星
            self.connectStars = {{row, col} }
            self:checkStar(row, col)
            if #self.connectStars >= 2 then
                -- 选中星星
                self:selectStar()
                self:showPreScore(row, col)
                self.isPreSelected = true
            else
                self.isPreSelected = false
            end
        end
    else
        print("没在选中状态")
        -- 相连的星星
        self.connectStars = {{row, col} }
        self:checkStar(row, col)
        if #self.connectStars >= 2 then
            -- 选中星星
            self:selectStar()
            self:showPreScore(row, col)
            self.isPreSelected = true
        end
    end
end

function GameScene:selectStar()
    print("GameScene:selectStar")
    for i, v in ipairs(self.connectStars) do
        local row, col = v[1], v[2]
        self.starSpriteTable[row][col]:runAction(cc.RepeatForever:create(cc.Sequence:create(
            cc.RotateTo:create(0.1, 10),
            cc.RotateTo:create(0.1, -10)
        )))
    end
end
-- 显示将会获得的分数（仅用于双击模式）,需要提供要显示的位置的行列值
function GameScene:showPreScore(row, col)
    self.preScoreLabel:setString("+".. tostring(GameCfg.calcClearScore(#self.connectStars)))
    self.preScoreLabel:setPosition(
        self.gridLayer:getContentSize().width/GameCfg.gridCol * (col -0.5),
        self.gridLayer:getContentSize().height/GameCfg.gridRow * (row -0.5) + (display.height - self.gridLayer:getContentSize().height) / 2)
    if self.preScoreLabel:getPositionX() - self.preScoreLabel:getContentSize().width/2 < 0 then
        self.preScoreLabel:setPositionX(self.preScoreLabel:getContentSize().width/2)
    elseif self.preScoreLabel:getPositionX() + self.preScoreLabel:getContentSize().width/2 > display.width then
        self.preScoreLabel:setPositionX(display.width - self.preScoreLabel:getContentSize().width/2)
    end
    self.preScoreLabel:setVisible(true)
end
-- 隐藏将会获得的分数（仅用于双击模式）
function GameScene:hidePreScore()
    self.preScoreLabel:setVisible(false)
end
function GameScene:diselectStar()
    print("GameScene:diselectStar")
    for i, v in ipairs(self.connectStars) do
        local row, col = v[1], v[2]
        self.starSpriteTable[row][col]:stopAllActions()
        self.starSpriteTable[row][col]:setRotation(0)
    end
end
-- 清除一次
-- @param 点击时的坐标，用于确定加分效果显示的位置
function GameScene:cleanOnce(row, col)
    print("self.connectStars", #self.connectStars)

    -- 播放声音
    Util.playEffect()
    -- 提示得分情况
    local fontSize = 80
    if #self.connectStars >= 6 then
        fontSize = 250
    elseif #self.connectStars >= 4 then
        fontSize = 150
    end
    local addScore = GameCfg.calcClearScore(#self.connectStars)
    local addScoreLabel = cc.Label:create()
    addScoreLabel:setString("+".. addScore)
    addScoreLabel:setTextColor(ColorCfg.white)
    addScoreLabel:setSystemFontSize(fontSize)
    addScoreLabel:setPosition(
        self.gridLayer:getContentSize().width/GameCfg.gridCol * (col -0.5),
        self.gridLayer:getContentSize().height/GameCfg.gridRow * (math.min(row, GameCfg.gridRow-3) + 1))
    if addScoreLabel:getPositionX() - addScoreLabel:getContentSize().width/2 < 0 then
        addScoreLabel:setPositionX(addScoreLabel:getContentSize().width/2)
    elseif addScoreLabel:getPositionX() + addScoreLabel:getContentSize().width/2 > self.gridLayer:getContentSize().width then
        addScoreLabel:setPositionX(self.gridLayer:getContentSize().width - addScoreLabel:getContentSize().width/2)
    end
    addScoreLabel:setOpacity(0)
    local showingAction = cc.DelayTime:create(0.7)
    if #self.connectStars >= 20 then
        showingAction = cc.Blink:create(6, 24)
    elseif #self.connectStars >= 15 then
        showingAction = cc.Blink:create(3, 12)
    elseif #self.connectStars >= 10 then
        showingAction = cc.DelayTime:create(2)
    end
    addScoreLabel:runAction(cc.Sequence:create(
        cc.Spawn:create(cc.FadeIn:create(0.1), cc.MoveBy:create(0.1, cc.p(0, 20))),
        showingAction,
        cc.Spawn:create(cc.FadeOut:create(0.1), cc.MoveBy:create(0.1, cc.p(0, 20))),
        cc.CallFunc:create(function() addScoreLabel:removeFromParent() end)
    ))
    self.gridLayer:addChild(addScoreLabel, 10)

    -- 计分
    self.score = self.score + addScore
    self:refreshScore()
    -- 清除星星
    self:clearConnectStar()
    -- 让星星下落
    self:fallDownStar()
    -- 让星星往左靠
    self:fallLeftStar()

    -- 检测本关是否结束
    if self:checkOver() then
        print("不能再消除了")
        if self.score > self.highScore then
            -- 破记录了
            self.highScore = self.score
            cc.UserDefault:getInstance():setIntegerForKey("highScore", self.highScore)
            cc.UserDefault:getInstance():flush()
        end
        self:checkNextLevel()
    end
end
function GameScene:restartGame()
    print("GameScene:restartGame")
    if self.score > self.highScore then
        -- 破记录了
        self.highScore = self.score
        cc.UserDefault:getInstance():setIntegerForKey("highScore", self.highScore)
        cc.UserDefault:getInstance():flush()
    end

    self.level = cc.UserDefault:getInstance():getIntegerForKey("highLevel", 1)
    self.score = cc.UserDefault:getInstance():getIntegerForKey("highLevelScore", 0)
    self:initGrid()
    self:refreshLevelInfo()
    self:refreshScore()
end
--[[
初始化网格数据
 ]]
function GameScene:initGrid()
    self.gridLayer:removeAllChildren()
    -- 网格数据
    self.grid = {}
    -- 网格精灵（星星）
    self.starSpriteTable = {}
    local starCellWidth = self.gridLayer:getContentSize().width/GameCfg.gridCol
    local starCellHeight = self.gridLayer:getContentSize().height/GameCfg.gridRow
    for i=1,GameCfg.gridRow do
        self.grid[i] = {}
        self.starSpriteTable[i] = {}
        for j=1,GameCfg.gridCol do
            self.grid[i][j] = math.random(1,GameCfg.starTypeCount)
            local starSprite = cc.Sprite:create("star.png")
            starSprite:setScaleX(
                starCellWidth / starSprite:getContentSize().width * GameCfg.starContentSizePercent)
            starSprite:setScaleY(
                starCellHeight / starSprite:getContentSize().height * GameCfg.starContentSizePercent)
            starSprite:setPosition(
                (j-0.5)*starCellWidth,
                (i-0.5)*starCellHeight)
            starSprite:setColor(ColorCfg["star".. self.grid[i][j]])
            self.gridLayer:addChild(starSprite)
            self.starSpriteTable[i][j] = starSprite
        end
    end
end
--[[
检测一个星星
 ]]
function GameScene:checkStar(row, col)
    local starType = self.grid[row][col]
    -- 要扫描的4个星星（上下左右）
    local scanStar = {{row+1, col},{row-1, col},{row, col-1},{row, col+1} }
    for i,v in ipairs(scanStar) do
        local scanRow, scanCol = v[1], v[2]
        if self:inGrid(scanRow, scanCol) and self.grid[scanRow][scanCol] == starType and not self:connectContain(scanRow, scanCol) then
            table.insert(self.connectStars, {scanRow, scanCol})
            self:checkStar(scanRow, scanCol)
        end
    end
end
-- 在相连星星数组里，找，有没有这个星星
function GameScene:connectContain(row, col)
    for i, v in ipairs(self.connectStars) do
        if v[1] == row and v[2] == col then
            return true
        end
    end
    return false
end
--在没在网格内
function GameScene:inGrid(row, col)
    if row >= 1
            and row <= GameCfg.gridRow
            and col >= 1
            and col <= GameCfg.gridCol
            then
        return true
    else
        return false
    end
end

--消除相连的星星
function GameScene:clearConnectStar()
    for i,v in ipairs(self.connectStars) do
        local row, col = v[1], v[2]
        -- 数据里记为0
        self.grid[row][col] = 0
        -- 播放粒子效果
--        local particle = cc.ParticleSystemQuad:create("particle1.plist")
--        particle:setPosition(self.starSpriteTable[row][col]:getPosition())
--        self.gridLayer:addChild(particle, 1000)
        -- 移除精灵
        self.starSpriteTable[row][col]:removeFromParent()
    end
end

-- 下落星星
function GameScene:fallDownStar()
    -- 下落数组（用于记录哪些星星需要下落）（记录格式为{row,col,下落的距离）
    local fallDownTable = {}
    -- 遍历每一列
    for col = 1,GameCfg.gridCol do
        -- 下落的距离
        local fallDistance = 0
        -- 从下往上，遍历每一个星星
        for row = 1,GameCfg.gridRow do
            -- 如果是空，则增加一个下落距离
            if self.grid[row][col] == 0 then
                fallDistance = fallDistance + 1
            end
            -- 如果需要下落且当前不是空，就记录到下落数组里
            if fallDistance > 0 and self.grid[row][col] > 0 then
                table.insert(fallDownTable, {row, col, fallDistance})
            end
        end
    end
    -- 处理下落数组
    for i,v in ipairs(fallDownTable) do
        local row, col, fallDistance = v[1],v[2],v[3]
        self.grid[row-fallDistance][col] = self.grid[row][col]
        self.grid[row][col] = 0
        self.starSpriteTable[row-fallDistance][col] = self.starSpriteTable[row][col]
        self.starSpriteTable[row][col] = nil
        -- 让精灵下落
        self.starSpriteTable[row-fallDistance][col]:stopAllActions()
        self.starSpriteTable[row-fallDistance][col]:runAction(cc.MoveTo:create(GameCfg.fallDownTime, cc.p(
            (col-0.5)*(self.gridLayer:getContentSize().width/GameCfg.gridCol),
            (row-fallDistance-0.5)*(self.gridLayer:getContentSize().height/GameCfg.gridRow)
            )))
    end
end
-- 左靠星星
function GameScene:fallLeftStar()
    -- 左靠数组（数据格式为{col, fallLeftDistance}）
    local fallLeftTable = {}
    -- 左靠距离
    local fallLeftDistance = 0
    -- 遍历每一列,找到需要左靠的所有列
    for col = 1,GameCfg.gridCol do
        local emptyCol = true
        for row = 1, GameCfg.gridRow do
            if self.grid[row][col] > 0 then
                -- 只要本列找到一个星星，就不是空列
                emptyCol = false
                break
            end
        end
        if emptyCol then
            -- 如果是空列
            fallLeftDistance = fallLeftDistance + 1
        end

        -- 如果不是空列，并且需要左靠，就记录到左靠数组里
        if not emptyCol and fallLeftDistance > 0 then
            table.insert(fallLeftTable, {col, fallLeftDistance})
        end
    end

    -- 左靠所有需要左靠的列
    for i,v in ipairs(fallLeftTable) do
        local col, fallLeftDistance2 = v[1], v[2]
        for row = 1, GameCfg.gridRow do
            if self.grid[row][col] > 0 then
                self.grid[row][col-fallLeftDistance2] = self.grid[row][col]
                self.grid[row][col] = 0
                self.starSpriteTable[row][col-fallLeftDistance2] = self.starSpriteTable[row][col]
                self.starSpriteTable[row][col] = nil
                -- 让精灵下落
                local delayAction = cc.DelayTime:create(GameCfg.fallDownTime)
                local moveAction = cc.MoveTo:create(GameCfg.fallLeftTime, cc.p(
                    (col-fallLeftDistance2-0.5)*(self.gridLayer:getContentSize().width/GameCfg.gridCol),
                    (row-0.5)*(self.gridLayer:getContentSize().height/GameCfg.gridRow)))

                self.starSpriteTable[row][col-fallLeftDistance2]:stopAllActions()
                self.starSpriteTable[row][col-fallLeftDistance2]:runAction(cc.Sequence:create(delayAction,moveAction))
            else
                -- 只要有一个是空，上面的肯定都是空了
                break
            end
        end
    end
end

-- 检测是否不能再消了
function GameScene:checkOver()
    -- 先遍历列，效率高一些，因为如果一个星星为空，那上面一定没有星星了
    for col = 1, GameCfg.gridCol do
        for row = 1, GameCfg.gridRow do
            local starType = self.grid[row][col]
            if starType == 0 then break end
            -- 要扫描的4个星星（上下左右）
            local scanStar = {{row+1, col},{row-1, col},{row, col-1},{row, col+1} }
            for i,v in ipairs(scanStar) do
                local scanRow, scanCol = v[1], v[2]
                -- 如果被扫描的4个中有相连的，就直接返回false
                if self:inGrid(scanRow, scanCol) and self.grid[scanRow][scanCol] == starType then
                    return false
                end
            end
        end
    end
    return true
end

-- 检测是否能到下一关，并且做出反应
function GameScene:checkNextLevel()
    -- 禁用重玩和关闭
    self.disableRestartAndClose = true
    local lastCount = self:countLastStar()
    self.score = self.score + GameCfg.calcLastScore(lastCount)


--    self:runAction(cc.Sequence:create(
--        cc.DelayTime:create(GameCfg.toNextLevelTime),
--        cc.CallFunc:create(function)))
    local function tipLastScore()
        self:refreshScore()
        self:showTip("剩余".. lastCount.."个\n奖励"..GameCfg.calcLastScore(lastCount))
    end
    local function tipGameOver()
        self:showTip("Game Over")
    end
    local function tipSuccess()
        self:showTip("闯关成功\n进入下一关")
    end
    local function nextLevel()
        self.level = self.level + 1
        self:initGrid()
        self:refreshLevelInfo()
        -- 记录最高关卡
        cc.UserDefault:getInstance():setIntegerForKey("highLevel", self.level)
        cc.UserDefault:getInstance():setIntegerForKey("highLevelScore", self.score)
        cc.UserDefault:getInstance():flush()
        -- 启用重玩和关闭按钮
        self.disableRestartAndClose = nil
    end
    local function overBack()
        -- 启用重玩和关闭按钮，不过好像也没有什么意义了
        self.disableRestartAndClose = nil
        self:getApp():enterScene("MainScene")
    end
    if self.score >= GameCfg.calcTargetScore(self.level) then
        -- 闯关成功
        self:runAction(cc.Sequence:create(
            cc.DelayTime:create(0.5),
            cc.CallFunc:create(tipLastScore),
            cc.DelayTime:create(GameCfg.tipTime+0.6),
            cc.CallFunc:create(tipSuccess),
            cc.DelayTime:create(GameCfg.tipTime+0.6),
            cc.CallFunc:create(nextLevel)
        ))
    else
        -- 闯关失败
        self:runAction(cc.Sequence:create(
            cc.DelayTime:create(0.5),
            cc.CallFunc:create(tipLastScore),
            cc.DelayTime:create(GameCfg.tipTime+0.6),
            cc.CallFunc:create(tipGameOver),
            cc.DelayTime:create(GameCfg.tipTime+0.6),
            cc.CallFunc:create(overBack)
        ))
    end


end
-- 数一下还剩多少个星星
function GameScene:countLastStar()
    local count = 0
    for col = 1, GameCfg.gridCol do
        for row = 1, GameCfg.gridRow do
            if self.grid[row][col] > 0 then
                count = count + 1
            else
                break
            end
        end
    end
    return count
end
--显示提示信息
function GameScene:showTip(msg)
    local pos1 = cc.p(self.tipLayer:getContentSize().width*2, self.tipLayer:getContentSize().height/2)
    local pos2 = cc.p(self.tipLayer:getContentSize().width/2, self.tipLayer:getContentSize().height/2)
    local pos3 = cc.p(-self.tipLayer:getContentSize().width, self.tipLayer:getContentSize().height/2)
    self.tipLabel:setString(msg)
    self.tipLabel:setPosition(pos1)
    self.tipLabel:stopAllActions()
    self.tipLayer:setOpacity(255)
    self.tipLabel:runAction(cc.Sequence:create(
        cc.Spawn:create(cc.FadeIn:create(0.3), cc.MoveTo:create(0.3, pos2)),
        cc.DelayTime:create(GameCfg.tipTime),
        cc.Spawn:create(cc.FadeOut:create(0.3), cc.MoveTo:create(0.3, pos3)),
        cc.CallFunc:create(function() self.tipLayer:setOpacity(0) end)
    ))
end

function GameScene:onEnter()
    print("onEnter")
--    cc.SimpleAudioEngine:getInstance():playBackgroundMusic("MusicGame.ogg", true)
end
function GameScene:onExit()
    print("onExit")
--    cc.SimpleAudioEngine:getInstance():stopBackgroundMusic()
end
return GameScene
